package cn.itcast.bos.service.take_delivery.impl;

import java.util.Date;
import java.util.Iterator;
import java.util.Set;
import java.util.UUID;

import javax.annotation.Resource;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.Session;
import javax.ws.rs.core.MediaType;

import org.apache.activemq.broker.region.Destination;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.cxf.jaxrs.client.WebClient;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.itcast.bos.constants.Constants;
import cn.itcast.bos.dao.base.AreaRepository;
import cn.itcast.bos.dao.base.FixedAreaRepository;
import cn.itcast.bos.dao.take_delivery.OrderRepository;
import cn.itcast.bos.dao.take_delivery.WorkBillRepository;
import cn.itcast.bos.domain.base.Area;
import cn.itcast.bos.domain.base.Courier;
import cn.itcast.bos.domain.base.FixedArea;
import cn.itcast.bos.domain.base.SubArea;
import cn.itcast.bos.domain.take_delivery.Order;
import cn.itcast.bos.domain.take_delivery.WorkBill;
import cn.itcast.bos.service.take_delivery.OrderService;

@Service
@Transactional
public class OrderServiceImpl implements OrderService {
	@Resource
	private FixedAreaRepository fixedAreaDao;

	@Resource
	private AreaRepository areaDao;

	@Resource
	private OrderRepository orderDao;

	@Resource
	private WorkBillRepository workBillDao;

	// 保存订单
	@Override
	public void saveOrder(Order order) {

		// order订单基础数据 设定
		order.setOrderNum(UUID.randomUUID().toString());// 订单编号
		order.setOrderTime(new Date());// 设置下单时间 注意 现在一定会提到 页面
		order.setStatus("1"); // 待取件
		// 重置寄件人区域 持久态
		Area sendArea = areaDao.findByProvinceAndCityAndDistrict(order.getSendArea().getProvince(),
				order.getSendArea().getCity(), order.getSendArea().getDistrict());
		order.setSendArea(sendArea);

		// 重置收件人区域持久态
		Area recArea = areaDao.findByProvinceAndCityAndDistrict(order.getRecArea().getProvince(),
				order.getRecArea().getCity(), order.getRecArea().getDistrict());
		order.setRecArea(recArea);
		// 已登录
		// 自动分单
		if (order.getCustomer_id() != null && order.getCustomer_id() != 0) {
			// 获取用户id 与详细地址 查询 crm系统客户地址表
			String fixedAreaId = WebClient
					.create(Constants.CRM_MANAGEMENT_URL + "/services/customerService/findFixedAreaId/"
							+ order.getCustomer_id() + "/" + order.getSendAddress())
					.accept(MediaType.APPLICATION_JSON).get(String.class);
			if (fixedAreaId != null) {
				// 查询定区
				FixedArea fixedArea = fixedAreaDao.findOne(fixedAreaId);
				// 根据当前下单时间 获得 匹配上班的快递员
				if (fixedArea.getCouriers() != null && fixedArea.getCouriers().size() > 0) {
					Iterator<Courier> iterator = fixedArea.getCouriers().iterator();
					if (iterator.hasNext()) {
						Courier courier = iterator.next();
						if (courier != null) {
							System.out.println("自动分单成功");
							saveOrder(order, courier);
							// 生成工单，通知快递员
							generateWorkBill(order);
							return;
						}
					}
				}
			}
		}
		// 未登录
		// 基于 区域 获取分区 匹配关键字 自动分单
		Set<SubArea> subAreas = sendArea.getSubareas();
		for (SubArea subArea : subAreas) {
			// 判断当前下单的地址是否包含分区的关键字 与辅助关键字
			if (order.getSendAddress().contains(subArea.getKeyWords())
					|| order.getSendAddress().contains(subArea.getAssistKeyWords())) {
				// 匹配到分区关键字 获取定区数据
				FixedArea fixedArea = subArea.getFixedArea();
				// 根据下单时间 匹配上班的快递员
				// 判断 当前分区 是否关联 定区数据 如果没有一定会报错
				Courier courier = fixedArea.getCouriers().iterator().next();// 获取快递员信息

				if (courier != null) {
					// 自动分单成功
					System.out.println("自动分单成功");
					saveOrder(order, courier);

					// 生成工单，发送短信
					generateWorkBill(order);
					return;
				}
			}
		}
		// 人工调度分单
		order.setOrderType("2");
		orderDao.save(order);
	}

	@Resource(name = "jmsQueueTemplate")
	private JmsTemplate jmsTemplate;

	private void generateWorkBill(final Order order) {
		WorkBill workBill = new WorkBill();
		workBill.setType("新");
		workBill.setPickstate("新单");
		workBill.setBuildtime(new Date());
		workBill.setRemark(order.getRemark());
		final String smsNumber = RandomStringUtils.randomNumeric(4);
		workBill.setSmsNumber(smsNumber); // 短信序号
		workBill.setOrder(order);
		workBill.setCourier(order.getCourier());
		workBillDao.save(workBill);
		// 调用MQ消息队列,给用户发送一条短息
		jmsTemplate.send("bos_sms", new MessageCreator() {

			@Override
			public Message createMessage(Session session) throws JMSException {
				MapMessage mapMessage = session.createMapMessage();
				mapMessage.setString("telephone", order.getCourier().getTelephone());
				mapMessage.setString("msg", "短信序号：" + smsNumber + ",取件地址：" + order.getSendAddress() + ",联系人:"
						+ order.getSendName() + ",手机:" + order.getSendMobile() + "，快递员捎话：" + order.getSendMobileMsg());
				return mapMessage;
			}
		});
		workBill.setPickstate("已通知");
	}

	// 保存订单
	private void saveOrder(Order order, Courier courier) {
		// 将快递员关联到 订单
		order.setCourier(courier);
		// 设置自动分单
		order.setOrderType("1");
		// 保存订单
		orderDao.save(order);
	}

	@Override
	public Order findByOrderNum(String orderNum) {
		return orderDao.findByOrderNum(orderNum);
	}
}
